define([
    'text!planmanage/addfileplan/templates/AddFilePlan_fourth.html',
    'planmanage/addfileplan/views/AddFilePlan_variable'
], function(AddFilePlanFourthViewTpl, VariableView) {
    // 文件名匹配规则配置gird
    var $grid;
    var gridData_delete = [];
    var fileType_old = "0";
    return fish.View.extend({
        template: fish.compile(AddFilePlanFourthViewTpl),
        i18nData: fish.extend({}),
        events: {
            'click #fileName_add': 'fileNameAdd',
            'click #buttonFileNameVerify': 'buttonFileNameVerify'
        },

        initialize: function() {
            // 验证并获取条件信息配置表单数据
            fish.on('getConditionFileFormData', $.proxy(this.getConditionFileFormData, this));
            // 条件信息配置表单数据回绑
            fish.on('setConditionFileForm', $.proxy(this.setConditionFileForm, this));
        },

        serialize: function() {
            return this.i18nData;
        },

        //这里用来初始化页面上要用到的fish组件
        afterRender: function() {
            var me = this;
            // 搜索范围
            $('input[name="scanRange"]').combobox({
                placeholder : "请选择搜索范围",
                dataTextField : "name",
                dataValueField : "value",
                setEditable : false,
                value : "0",
                dataSource : [ {
                    name : "当前目录",
                    value : "0"
                }, {
                    name : "当前目录和所有子目录",
                    value : "1"
                }]
            });

            // 文件类型
            $('input[name="fileType"]').combobox({
                placeholder : "请选择文件类型",
                dataTextField : "name",
                dataValueField : "value",
                setEditable : false,
                value : "0",
                dataSource : [ {
                    name : "不限",
                    value : "0"
                }, {
                    name : "d - 目录",
                    value : "1"
                }, {
                    name : "f - 普通文件",
                    value : "2"
                }],
                change: me.fileTypeChange
            });

            // 文件名匹配规则配置 控件
            $('input[name="fileName"]').fileName({
                dataTextField : "name",
                dataValueField : "value",
                addMenuWidth:120,
                value:[{type:'contain',value:'包含'}]
            });
        },

        fileTypeChange: function(){
            var fileType = $("#conditionFileForm").form("value").fileType;
            if(!$grid || $grid.grid("getRowData").length == 0){                
                return;
            }
            var fileNameGridData = $grid.grid("getRowData");
            // 之前长什么样，干掉
            if(fileType_old != "0"){// 目录或者文件
                for(var i = 0; i < fileNameGridData.length; i++){
                    fileNameGridData[i].fileName = 
                    fileNameGridData[i].fileName.substring(8,
                    fileNameGridData[i].fileName.length);
                    if(fileNameGridData[i].fileNameStr_OK == undefined){
                        continue;
                    }
                    fileNameGridData[i].fileNameStr = 
                    fileNameGridData[i].fileNameStr.substring(8,
                    fileNameGridData[i].fileNameStr.length);
                    fileNameGridData[i].fileNameStr_OK = 
                    fileNameGridData[i].fileNameStr_OK.substring(8,
                    fileNameGridData[i].fileNameStr_OK.length);
                }
            }
            // 拼接现在的
            var headStr = "";
            if(fileType == "1"){// 目录
                headStr = "-type d ";
            }else if(fileType == "2"){// 文件
                headStr = "-type f ";
            }
            for(var i = 0; i < fileNameGridData.length; i++){
                fileNameGridData[i].fileName = headStr + fileNameGridData[i].fileName;
                if(fileNameGridData[i].fileNameStr_OK){
                    fileNameGridData[i].fileNameStr = headStr + fileNameGridData[i].fileNameStr;
                    fileNameGridData[i].fileNameStr_OK = headStr + fileNameGridData[i].fileNameStr_OK;
                }
                $grid.grid("delRowData", fileNameGridData[i]._id_);
                $grid.grid("addRowData", fileNameGridData[i]);
            }
            fileType_old = fileType;
        },

        fileNameAdd: function(fileNameObj){
            $('input[name="fileName"]').fileName('value');

            $('#fileNameGrid_div').removeClass("hidden");
            // 文件名匹配规则配置 预览
            $grid = $("#fileName_grid").grid({
                height: 110,
                colModel: [{
                    name: 'fileName',
                    label: '规则配置预览',
                    overflow: 'auto',
                    sortable: false
                }, {
                    name: 'fileNameStr',
                    label: '传给后台解析',
                    sortable: false,
                    hidden: true
                }, {
                    name: 'dirOrder',
                    label: '后台传出来的序号',
                    sortable: false,
                    hidden: true
                }, {
                    name: 'fileNameStr_OK',
                    label: '后台传出来的',
                    sortable: false,
                    hidden: true
                }, {
                    name: '',
                    formatter: 'actions',
                    classes: 'text-primary',
                    width: 10,
                    sortable: false,
                    formatoptions: {
                        editbutton: false, //默认开启编辑功能
                        delbutton: true //默认开启删除功能
                    }
                }],
                afterDeleteRow: function (e, rowid, data, option) {
                    var rowNum = $grid.grid("getGridParam", "records");
                    if(rowNum == 0){
                        $('#fileNameGrid_div').addClass("hidden");
                    }
                    if(data.dirOrder){
                        data.isDelete = 1;
                        delete data._id_;
                        delete data.xpath;
                        delete data.xpathStr;
                        delete data.fileName;
                        gridData_delete.push(data);
                    }
                    VariableView.setFileName_OK(false);
                }
            });
            if(fileNameObj.type == "click"){// 新增
                var fileNames = $.parseJSON($('input[name="fileName"]').val());
                var fileName = "-type f ";
                var fileType = $("#conditionFileForm").form("value").fileType;
                if(fileType == "0"){// 不限
                    fileName = "";
                }else if(fileType == "1"){// 目录
                    fileName = "-type d ";
                }
                var priority = 1;
                for(var i = 0; i < fileNames.length; i++){
                    if ("contain" == fileNames[i].type) {// 包含
                        fileName += "' ";
                        fileName += "-name '";
                        continue;
                    } else if ("noContain" == fileNames[i].type) {// 不包含
                        fileName += "' ";
                        fileName += "! -name '";
                        continue;
                    } else if ("timer" == fileNames[i].type) {// 时间变量
                        fileName += "${" + priority + "}";
                        priority++;
                    } else if ("list" == fileNames[i].type) {// 可转换变量
                        fileName += "${" + priority + "}";
                        priority++;
                    } else if ("4" == fileNames[i].type) {// 账期
                        fileName += "${" + priority + "}";
                        priority++;
                    } else if ("nowDate" == fileNames[i].type) {// 当前年月日
                        fileName += "${" + priority + "}";
                        priority++;
                    } else if ("nowDateWithSplit" == fileNames[i].type) {// 当前年-月-日
                        fileName += "${" + priority + "}";
                        priority++;
                    }else {
                        fileName += fileNames[i].value;
                    }
                }
                fileName += "'";
                if(fileType != "0"){// 不限
                    fileName = fileName.substring(0, 8) + fileName.substring(10, fileName.length);
                }else{
                    fileName = fileName.substring(2, fileName.length);
                }
                $grid.grid("addRowData", {'fileNameStr': $('input[name="fileName"]').val(), 'fileName': fileName});
            }else{
                $grid.grid("addRowData", fileNameObj);
            }
            VariableView.setFileName_OK(false);
        },

        // 结果脚本预览 按钮点击事件
        buttonFileNameVerify: function(){
            if(!$grid || $grid.grid("getRowData").length == 0){                
                $('textarea[name="fileName_show"]').val('');
                fish.toast('warn','请配置文件名匹配规则');
            }else{
                var fileNameGridData = $grid.grid("getRowData");
                var data = VariableView.getPlanFormData();
                data.fileNameGridDataStr = this.getGridDataStr($grid.grid("getRowData"));
                data.act = act;
                data.fileType = $("#conditionFileForm").form("value").fileType;
                if(act == 'edit' || act == 'draft'){
                    data.sourceDataId = VariableView.getSourceDataId();
                }
                fish.ajax({
                    async : false,
                    url: ctx + '/baseconfig/dmfileplan/fileNameVerify.do',
                    showMask: false,  //是否自动显式全局遮罩
                    showError: true, //在出现异常时自动显示异常信息，后台需要返回的数据格式：{code:'ERROR-1001',message:'登录失败'}
                    timeout: 30000,   //超过3秒显式全局遮罩，此参数在showMask为true时才有效
                    data: data,
                    beforeSend: function(){
                        $.blockUI({message : "文件名匹配规则验证中,请稍候..."});
                    },
                    complete: function(xhr, status){
                        $.unblockUI();
                        if(status == 'timeout'){
                            fish.toast('error', "网络请求超时");
                            return;
                        }
                        $('textarea[name="fileName_show"]').val('');
                        var fileName = "";
                        var fileNameList = xhr.responseJSON.fileNameList;
                        for(var i = 0; i < fileNameList.length - 1; i++){
                            fileName += fileNameList[i]+"\n";
                        }
                        if(xhr.responseJSON.fileNameIsOK){// 验证通过
                            VariableView.setFileName_OK(true);
                        }else{
                            fileName = "ERROR:\n" + fileName;
                            VariableView.setFileName_OK(false);
                        }
                        $('textarea[name="fileName_show"]').val(fileName);
                    },
                    //【注意】如果你在这里配置了自己的error处理函数，fish.ajax就不会自动帮你显示异常信息了！
                    error:function(){
                        $.unblockUI();
                    }
                });
            }
        },

        // 获取条件配置表单数据
        getConditionFileFormData: function(){
            var conditionFileFormData = $("#conditionFileForm").form("value");
            // 判断有没有配置文件名匹配规则
            if(!$grid){
                fish.toast('warn','请配置文件名匹配规则');
                VariableView.setConditionFileForm_OK(false);
            }else{
                if(VariableView.getFileName_OK()){
                    conditionFileFormData.fileNameGridDataStr = this.getGridDataStr($grid.grid("getRowData"));
                    VariableView.setConditionFileFormData(conditionFileFormData);
                    VariableView.setConditionFileForm_OK(true);
                }else{
                    fish.toast('warn','文件名匹配规则配置未验证或验证不通过，请点击“结果预览”按钮进行验证');
                    VariableView.setConditionFileForm_OK(false);
                }
            }
        },

        // 获取有用的gridData，并转成String
        getGridDataStr: function(gridData){
            var newGridData = [];
            for(var i = 0; i < gridData.length; i++){
                var oneData = {};
                if(gridData[i].fileNameStr_OK != ''){// 说明是从后台传回来的完整的
                    oneData.fileNameStr_OK = gridData[i].fileNameStr_OK;
                    oneData.dirOrder = gridData[i].dirOrder;
                }
                oneData.fileNameStr = gridData[i].fileNameStr;
                newGridData.push(oneData);
            }
            for(var i = 0; i < gridData_delete.length; i++){
                newGridData.push(gridData_delete[i]);
            }
            return JSON.stringify(newGridData);
        },

        // 条件信息配置表单数据回绑
        setConditionFileForm: function(){
            var data = VariableView.getDmStrategyInfo();
            fileType_old = data.fileType+"";
            // 搜索范围
            $('input[name="scanRange"]').combobox('value',data.scanRange+"");
            // 文件类型
            $('input[name="fileType"]').combobox('value',data.fileType+"");
            // 描述
            $('textarea[name="ruleDesc"]').val(data.ruleDesc);
            // 文件名匹配规则
            for(var i = 0; i < data.fileNameGridData.length; i++){
                data.fileNameGridData[i].fileName = data.fileNameGridData[i].fileNameStr;
                this.fileNameAdd(data.fileNameGridData[i]);
            }
            VariableView.setFileName_OK(true);
        }
    });
});